<template>
 <el-row id="cpts-collect-base-datas">
   <el-row v-if="!isViewShow" class="permission">
     没有权限!
   </el-row>
   <el-card v-else class="box-card">
     <div slot="header" class="clearfix">
       <span>采集基础数据</span>
       <el-button :disabled="!isViewEdit" style="padding: 6px 6px;margin-left: 1580px" type="primary" @click="handleAdd">新增</el-button>
       <el-button :disabled="!isViewEdit" style="padding: 6px 6px;" type="primary">导入</el-button>
       <el-button @click="reportTable" :disabled="!isViewEdit" style="padding: 6px 6px;" type="primary">导出</el-button>
     </div>

     <!--条件栏-->
     <el-row style="margin-bottom: 10px">
       <span>累计:</span>
       <el-select @change="onSelectChange" v-model="accumulationValue" placeholder="请选择">
         <el-option
           v-for="item in accumulationOptions"
           :key="item.value"
           :label="item.label"
           :value="item.value">
         </el-option>
       </el-select>
       <el-input
         v-model="searchStr"
         placeholder="请输入内容">
         <i slot="prefix" class="el-input__icon el-icon-search"></i>
       </el-input>

       <el-button :disabled="!isViewEdit" @click="onSubmitSearch">确定</el-button>
     </el-row>

     <!--表格栏-->
     <el-table
       :data="tableData"
       stripe
       border
       style="width: 100%;"
       max-height="600">
       <el-table-column
         align="center"
         prop="tagName"
         label="变量点名称">
       </el-table-column>
       <el-table-column
         align="center"
         :formatter="cumulativeFormatter"
         prop="isCumulative"
         label="是否累计">
       </el-table-column>
       <el-table-column
         align="center"
         prop="proportion"
         label="缩放因子">
       </el-table-column>
       <el-table-column
         align="center"
         prop="measuringInstrumentName"
         label="计量器具">
       </el-table-column>
       <el-table-column
         align="center"
         prop="equipmentName"
         label="所属设备">
       </el-table-column>
       <el-table-column
         align="center"
         prop="upLimit"
         label="最大值">
       </el-table-column>
       <el-table-column
         align="center"
         prop="downLimt"
         label="最小值">
       </el-table-column>
       <el-table-column
         align="center"
         prop="collectorName"
         label="采集来源">
       </el-table-column>
       <el-table-column
         align="center"
         prop="unit"
         label="单位">
       </el-table-column>

       <el-table-column label="操作"  align="center"  fixed="right" width="140px">
         <template slot-scope="scope">
           <el-button :disabled="!isViewEdit"
                      size="mini"
                      type="text"
                      @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
         <!--  <el-button :disabled="!isViewEdit"
             size="mini"
             type="text"
             @click="handleHistory(scope.$index, scope.row)">历史</el-button>-->
           <el-button :disabled="!isViewEdit"
             size="mini"
             type="text"
             @click="handleDelete(scope.$index, scope.row)">删除</el-button>
         </template>
       </el-table-column>
     </el-table>

     <!--分页-->
     <div style="text-align: center;margin-top: 10px;">
       <el-pagination
         background
         layout="prev, pager, next"
         :total="paginationCount"
         :current-page="currentPage"
         :page-size="pageSize"
         @current-change="currentChange">
       </el-pagination>
     </div>

   </el-card>

   <!--添加弹窗-->
   <el-dialog title="添加/编辑" :visible.sync="addDialogShow">
     <el-form :model="ruleForm" ref="ruleForm" :rules="rules"  label-width="100px">

       <el-row>
         <el-col :span="8">
           <el-form-item label="变量点名称" prop="tagName">
             <el-input :disabled="forbidden" v-model="ruleForm.tagName"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="ID" prop="tagId">
             <el-input :disabled="forbidden" v-model="ruleForm.tagId"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="变量类型" prop="whetherSwitch">
             <el-select :disabled="forbidden" placeholder="请选择类型"  v-model="ruleForm.whetherSwitch">
               <el-option
                 v-for="item in tagTypeFields"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
       </el-row>

       <el-row>
         <el-col :span="8">
           <el-form-item label="是否累计" prop="isCumulative">
             <el-select :disabled="forbidden" placeholder="请选择状态"  v-model="ruleForm.isCumulative">
               <el-option
                 v-for="item in fields"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="最大值" prop="upLimit">
             <el-input :disabled="forbidden" v-model="ruleForm.upLimit"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="最小值" prop="downLimt">
             <el-input :disabled="forbidden" v-model="ruleForm.downLimt"></el-input>
           </el-form-item>
         </el-col>
       </el-row>

       <el-row>
         <el-col :span="8">
           <el-form-item label="单位" prop="unit">
             <el-input :disabled="forbidden" v-model="ruleForm.unit"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="采集来源" prop="collectorName">
             <el-input :disabled="forbidden" v-model="ruleForm.collectorName"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="计量器具" prop="measuringInstrumentId">
             <el-select :disabled="forbidden" placeholder="请选择计量器具"  v-model="ruleForm.measuringInstrumentId">
               <el-option
                 v-for="item in measureFields"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>

       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="所属设备" prop="equipmentId">
             <el-select :disabled="forbidden" placeholder="请选择设备"  v-model="ruleForm.equipmentId">
               <el-option
                 v-for="item in deviceFields"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="死区(%)" prop="deadZone">
             <el-input type="number" :disabled="forbidden" v-model="ruleForm.deadZone"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="是否智能点">
             <el-select :disabled="forbidden" placeholder="请选择状态"  v-model="ruleForm.isAI">
               <el-option
                 v-for="item in aIFields"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
       </el-row>
       <el-row class="cbd-submit-layout">
         <el-button @click="submitAdd('ruleForm')" type="primary" :loading="false">提交</el-button>
       </el-row>

     </el-form>
   </el-dialog>

   <!--历史数据弹窗-->
   <el-dialog :visible.sync="dialogShow">
     <el-row slot="title">
       <span style="font-size: 18px">历史数据</span> <!-- <el-button style="margin-left: 760px; padding: 6px 10px"type="primary"  :loading="false">提交</el-button>-->
     </el-row>

     <el-row>
       <el-date-picker
         :type="pickerType"
         @change="onPickerChange"
         :value-format="histotyDateFormat"
         v-model="histotyDate"
         placeholder="选择日期时间">
       </el-date-picker>
     </el-row>

     <el-row>
       <BaseEchartsComponent ref="cptsCbdLineChart" :id="'cpts-cbd-chart'" :data="lineChartsOptions" />
     </el-row>

   </el-dialog>

 </el-row>
</template>

<script>
    import BaseEchartsComponent from "../BaseEcharts/index";
    import myEchartsOptions from '../../chart-options/echartsOptions'
    import {DateTime} from '../../utils/dateTime'
    export default {
      name: "collectBaseDatas",
      components: {BaseEchartsComponent},
      data(){
          return {
            isViewShow: false,
            isViewEdit: false,
            pickerType: 'date',
            histotyDateFormat: "yyyy-MM-dd",
            isAuto: 0,
            paginationCount: 0,
            currentPage:1,
            pageSize:10,
            forbidden: false,
            histotyDate: new Date(),
            deleteId: '',
            editId: '',
            queryHistoryId:'',
            tableData:[],
            addDialogShow: false,
            dialogShow:false,
            warnDialogShow:false,
            lineChartsOptions: this.validateGlobal.cloneObject(myEchartsOptions.lineChartsOption),
            fields:[{value: 0,label: '否'},{value: 1,label: '是'}],
            aIFields:[{value: 0,label: '否'},{value: 1,label: '是'}],
            tagTypeFields:[{value: 1,label: '离散型'},{value: 0,label: '数值型'}],
            deviceFields:[],
            measureFields:[],
            ruleForm: {
              isAI: 0,
              tagId: '',
              tagName: "",
              unit: "",
              equipmentId: "",
              measuringInstrumentId: '',
              isCumulative: '',
              whetherSwitch: '',
              upLimit: '',
              downLimt: '',
              collectorName: '',
              deadZone: ''
            },
            rules:{
              tagName:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
              tagId:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
              unit:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
              isCumulative:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
              whetherSwitch:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
              upLimit:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
              downLimt:[
                { required: true, message: '请输入', trigger: 'blur' },
              ],
            },
            runStatusValue: 1,
            runStatusOptions: [{label:"全部",value: 1},{label:"运行",value: 2},{label:"停机",value: 3}],
            accumulationValue:2,
            accumulationOptions: [{label:"全部",value: 2},{label:"是",value: 1},{label:"否",value: 0}],
            searchStr: '',
            isCumulative: '',
            editItem: '',
            pageStatus: 1,   // 1,新增   2，编辑

          }
    },
      mounted(){
        let obj = this.validateGlobal.getPermission(5)
        this.isViewShow = obj.isViewShow
        this.isViewEdit = obj.isViewEdit

        this.lineChartsOptions.xAxis[0].data = []
        this.lineChartsOptions.series[0].data = []
        this.lineChartsOptions.xAxis[0].axisLine.lineStyle.color = '#000'
        this.lineChartsOptions.yAxis[0].axisLine.lineStyle.color = '#000'
        this.lineChartsOptions.grid.left = 80
        this.askListsData()
        this.askDeviceList()
        this.askMeasureList()
      },
      methods:{
        reportTable: function(){
          let _that = this
          let num = ''
          for(let i=0;i < 10;i++){
            num += Math.ceil(Math.random() * 10)
          }
          let fileName  = new DateTime().getDate().trim()+ "_点表_" + num
          let url = this.ports.collectManage.collectBaseData.exportTable
          let userId = sessionStorage.getItem("userId")
          let gateway = sessionStorage.getItem("gateway")
          let askInfo = {
            name: '',
            userId: userId,
            current: 1,
            size: 1000,
            sn: gateway,
            isCumulative: _that.isCumulative
          }
          this.http.postExcel(url,askInfo,res => {
            console.log(res)
            const link = document.createElement('a')
            let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', fileName + '.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
        },
        onSubmitSearch: function(){
          this.askListsData()
        },
        onSelectChange: function(value){
          if (value === 2){
            this.isCumulative = ''
          }else{
            this.isCumulative = value
          }
        },
        statusFormatter(row, column) {
          if(row.isActive === 0){
            return '否'
          } else {
            return '是'
          }
        },

        cumulativeFormatter(row, column) {
          if(row.isCumulative === 0){
            return '否'
          } else {
            return '是'
          }
        },

        submitAdd: function (formName) {
          let _that = this
          this.$refs[formName].validate((valid) => {
            if (valid) {
              _that.postNewDatas()
            } else {
              _that.$message('输入有误!');
              return false;
            }
          });
        },

        handleAdd(){
          if (!this.addDialogShow){
            this.addDialogShow = true
          }
          this.pageStatus = 1
          this.resetForm()
          this.forbidden = false
        },

        handleEdit(index,item){
          if (!this.addDialogShow){
            this.addDialogShow = true
          }
          this.pageStatus = 2
          this.ruleForm = this.validateGlobal.cloneObject(item)
          this.editItem = item
        },

        handleHistory(index,item){
          this.isAuto = item.isAuto
          this.queryHistoryId = item.id
          if (!this.dialogShow){
            this.dialogShow = true
          }
          let dateTime = new DateTime()
          if (this.isAuto === 0) {
            this.pickerType = 'year'
            this.histotyDateFormat = 'yyyy'
            this.histotyDate = dateTime.getYear()
          }else{
            this.pickerType = 'date'
            this.histotyDateFormat = 'yyyy-MM-dd'
            this.histotyDate = dateTime.getDate2()
          }
          this.askHistoryDatas()
        },

        handleDelete(index,item){
          this.deleteId = item.id
          this.deleteItem()
        },

        handlerDeleteForWarn(){
          let _that = this
          this.deleteItem()
          this.warnDialogShow = false
        },

        resetForm: function(){   // 表单重置
        /*  if (this.$refs['ruleForm']!==undefined) {
            this.$refs['ruleForm'].resetFields();
          }*/
          this.ruleForm = {
            isAI: 0,
            tagName: "",
            unit: "",
            equipmentId: "",
            measuringInstrumentId: '',
            isCumulative: '',
            whetherSwitch: '',
            upLimit: '',
            downLimt: '',
            collectorName: '',
            deadZone: ''
          }
        },

        onPickerChange(value){
          this.histotyDate = value
          this.askHistoryDatas()
        },

        currentChange(currentPage){
          this.currentPage = currentPage;
          this.askListsData()
        },

        askListsData: function () {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let gateway = sessionStorage.getItem("gateway")
          console.log("gateway",gateway)
          let url = _that.ports.collectManage.collectBaseData.tagList
          let askData = {
            search: _that.searchStr,
            isCumulative: _that.isCumulative,
            userId: userId,
            current: _that.currentPage,
            size: _that.pageSize,
            sn:gateway,
          }
          this.http.get(url,askData, res => {
            console.log("myTagLists",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.tableData = res.data.records
              _that.paginationCount = res.data.total
            }else{
              _that.$message('列表获取失败!');
            }
          })
        },

        deleteItem:function () {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let url = _that.ports.collectManage.collectBaseData.delete
          let askData = {
            userId: userId,
            id:_that.deleteId,
          }
          this.http.get(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.$message('删除成功!');
              _that.askListsData()
            }else{
              _that.$message('删除失败!');
            }
          })
        },

        askHistoryDatas:function () {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let url = _that.ports.collectManage.collectBaseData.history
          let askData = {
            userId: userId,
            id: _that.queryHistoryId,
            time:_that.histotyDate,
            isAuto: _that.isAuto
          }
          this.http.get(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.lineChartsOptions.xAxis[0].data = res.data.times
              _that.lineChartsOptions.series[0].data = res.data.values
              _that.$refs.cptsCbdLineChart.drawLineGraph('cpts-cbd-chart',_that.lineChartsOptions)
            }else{
              _that.$message('请求失败!');
            }
          })
        },

        postNewDatas: function () {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let gateway = sessionStorage.getItem("gateway")
          let url = _that.ports.collectManage.collectBaseData.add + '?userId=' + userId
          let askData = this.ruleForm
          askData.sn = gateway
          this.http.post(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.$message('添加成功!');
              _that.addDialogShow = false
              _that.askListsData()
            }else{
              _that.$message('新增失败!');
            }
          })
        },

        askDeviceList: function() {
          let _that = this
          let gateway = sessionStorage.getItem("gateway")
          let url = _that.ports.deviceManage.list
          let askData = {
            sn: gateway,
            current: 1,
            size: 1000,
          }
          this.http.get(url,askData, res => {
            console.log("myDeviceList",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              if (!_that.validateGlobal.isEmpty(res.data.records)){
                let arry = []
                for(let i = 0;i<res.data.records.length;++i){
                  arry.push({label: res.data.records[i].deviceName,value:res.data.records[i].id})
                }
                _that.deviceFields = arry
                _that.ruleForm.equipmentId = arry[0].value
              }
            }else{
              _that.$message('设备获取失败!');
            }
          })
        },

        askMeasureList: function() {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let url = _that.ports.measureManage.query
          let askData = {
            userId: userId,
            current:1,
            size: 100
          }
          this.http.get(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              if (res.data.records){
                let arry = []
                for(let i = 0;i<res.data.records.length;++i){
                  arry.push({label: res.data.records[i].name,value:res.data.records[i].id})
                }
                _that.measureFields = arry
                _that.ruleForm.measuringInstrumentId = arry[0].value
              }
            }else{
              _that.$message('计量器具获取失败!');
            }
          })
        }

      }
    }
</script>

<style lang="scss">
#cpts-collect-base-datas{

  .el-input{
    width: 200px;
  }

  > .el-card{
    margin: 20px 20px 0 20px;
    height: 780px;
  }

  .el-dialog{
    #cpts-cbd-chart{
      height: 300px;
      width: 100%;
    }
  }

  .cbd-submit-layout{
    display: flex;
    justify-content: center;
  }
}
</style>
